// 游戏状态管理
class StroopGame {
    constructor() {
        this.currentScreen = 'main-menu';
        this.gameMode = null; // 'time' or 'life'
        this.correctAnswers = 0;
        this.totalAnswers = 0;
        this.lives = 3;
        this.timeLeft = 60;
        this.gameTimer = null;
        this.questionTimer = null;
        this.confirmationTimer = null;
        this.progressInterval = null;
        this.isGamePaused = false;
        this.isGameActive = false;
        this.isWaitingForConfirmation = false;
        
        // 游戏配置
        this.config = {
            progressBarDuration: 4000, // 进度条倒计时时间(ms) - 可配置
            enableProgressBar: true    // 是否启用进度条
        };
        
        // 颜色配置
        this.colors = {
            '红色': '#ef4444',
            '蓝色': '#3b82f6',
            '绿色': '#22c55e',
            '黄色': '#eab308',
            '紫色': '#a855f7',
            '橙色': '#f97316',
            '粉色': '#ec4899',
            '棕色': '#a16207',
            '青色': '#06b6d4',
            '灰色': '#6b7280'
        };
        
        this.colorNames = Object.keys(this.colors);
        this.currentQuestion = null;
        this.username = this.loadUsername();
        
        this.initializeEventListeners();
        this.showScreen('main-menu');
    }
    
    // 初始化事件监听器
    initializeEventListeners() {
        // 主菜单按钮
        document.getElementById('time-mode-btn').addEventListener('click', () => {
            this.checkUsernameAndStartGame('time');
        });
        
        document.getElementById('life-mode-btn').addEventListener('click', () => {
            this.checkUsernameAndStartGame('life');
        });
        
        document.getElementById('leaderboard-btn').addEventListener('click', () => {
            this.showLeaderboard();
        });
        
        document.getElementById('settings-btn').addEventListener('click', () => {
            this.showUsernameSetup();
        });
        
        // 用户名设置
        document.getElementById('confirm-username').addEventListener('click', () => {
            this.saveUsername();
        });
        
        document.getElementById('back-to-menu').addEventListener('click', () => {
            this.showScreen('main-menu');
        });
        
        // 游戏控制按钮
        document.getElementById('correct-btn').addEventListener('click', () => {
            this.answerQuestion(true);
        });
        
        document.getElementById('wrong-btn').addEventListener('click', () => {
            this.answerQuestion(false);
        });
        
        document.getElementById('pause-btn').addEventListener('click', () => {
            this.pauseGame();
        });
        
        // 暂停菜单
        document.getElementById('resume-btn').addEventListener('click', () => {
            this.resumeGame();
        });
        
        document.getElementById('restart-game-btn').addEventListener('click', () => {
            this.restartGame();
        });
        
        document.getElementById('quit-game-btn').addEventListener('click', () => {
            this.quitGame();
        });
        
        // 游戏结束按钮
        document.getElementById('restart-btn').addEventListener('click', () => {
            this.restartGame();
        });
        
        document.getElementById('back-menu-btn').addEventListener('click', () => {
            this.showScreen('main-menu');
        });
        
        // 排行榜关闭
        document.getElementById('close-leaderboard').addEventListener('click', () => {
            this.showScreen('main-menu');
        });
        
        // 键盘支持（移动端主要用触摸）
        document.addEventListener('keydown', (e) => {
            if (this.isGameActive && this.currentScreen === 'game-screen') {
                if (e.key === '1' || e.key === 'j' || e.key === 'J') {
                    this.answerQuestion(true);
                } else if (e.key === '2' || e.key === 'k' || e.key === 'K') {
                    this.answerQuestion(false);
                } else if (e.key === ' ' || e.key === 'Escape') {
                    e.preventDefault();
                    this.pauseGame();
                }
            }
        });
    }
    
    // 检查用户名并开始游戏
    checkUsernameAndStartGame(mode) {
        if (!this.username) {
            this.showUsernameSetup();
            this.pendingGameMode = mode;
        } else {
            this.startGame(mode);
        }
    }
    
    // 显示不同的屏幕
    showScreen(screenId) {
        const screens = ['main-menu', 'username-setup', 'game-screen', 'game-over', 'leaderboard-screen'];
        screens.forEach(id => {
            document.getElementById(id).classList.add('hidden');
        });
        document.getElementById(screenId).classList.remove('hidden');
        this.currentScreen = screenId;
    }
    
    // 用户名管理
    loadUsername() {
        return localStorage.getItem('stroop-username') || '';
    }
    
    saveUsername() {
        const input = document.getElementById('username-input');
        const username = input.value.trim();
        if (username) {
            this.username = username;
            localStorage.setItem('stroop-username', username);
            if (this.pendingGameMode) {
                this.startGame(this.pendingGameMode);
                this.pendingGameMode = null;
            } else {
                this.showScreen('main-menu');
            }
        } else {
            alert('请输入有效的用户名');
        }
    }
    
    showUsernameSetup() {
        this.showScreen('username-setup');
        const input = document.getElementById('username-input');
        input.value = this.username;
        input.focus();
    }
    
    // 游戏开始
    startGame(mode) {
        this.gameMode = mode;
        this.correctAnswers = 0;
        this.totalAnswers = 0;
        this.lives = 3;
        this.timeLeft = mode === 'time' ? 60 : 0;
        this.isGameActive = true;
        this.isGamePaused = false;
        this.isWaitingForConfirmation = false;
        
        this.showScreen('game-screen');
        this.updateUI();
        this.setupGameMode();
        this.generateQuestion();
    }
    
    // 设置游戏模式
    setupGameMode() {
        const timerLabel = document.getElementById('timer-label');
        const timerDisplay = document.getElementById('timer-display');
        
        if (this.gameMode === 'time') {
            timerLabel.textContent = '时间';
            timerDisplay.textContent = this.timeLeft;
            this.startTimer();
        } else {
            timerLabel.textContent = '生命';
            timerDisplay.textContent = '❤️'.repeat(this.lives);
        }
    }
    
    // 计时器
    startTimer() {
        this.gameTimer = setInterval(() => {
            if (!this.isGamePaused && this.isGameActive) {
                this.timeLeft--;
                document.getElementById('timer-display').textContent = this.timeLeft;
                
                if (this.timeLeft <= 0) {
                    this.endGame();
                }
            }
        }, 1000);
    }
    
    // 生成问题
    generateQuestion() {
        if (!this.isGameActive) return;
        
        // 使用所有颜色，固定50%正确概率
        const availableColors = this.colorNames;
        
        // 随机选择显示的文字和颜色
        const wordText = availableColors[Math.floor(Math.random() * availableColors.length)];
        const displayColor = availableColors[Math.floor(Math.random() * availableColors.length)];
        
        // 50%概率正确
        const isCorrect = Math.random() < 0.5;
        const finalDisplayColor = isCorrect ? wordText : displayColor;
        
        this.currentQuestion = {
            word: wordText,
            color: finalDisplayColor,
            isCorrect: wordText === finalDisplayColor
        };
        
        // 更新UI
        const colorWordElement = document.getElementById('color-word');
        colorWordElement.textContent = wordText;
        colorWordElement.style.color = this.colors[finalDisplayColor];
        
        // 添加动画效果
        colorWordElement.classList.remove('slide-in');
        void colorWordElement.offsetWidth; // 强制重排
        colorWordElement.classList.add('slide-in');
        
        // 统一启动进度条倒计时
        this.startProgressTimer(this.config.progressBarDuration);
    }
    
    // 统一进度条倒计时
    startProgressTimer(duration) {
        this.isWaitingForConfirmation = true;
        const progressContainer = document.getElementById('countdown-progress');
        const progressBar = document.getElementById('countdown-progress-bar');
        
        // 清除之前的计时器
        if (this.confirmationTimer) {
            clearTimeout(this.confirmationTimer);
        }
        if (this.progressInterval) {
            clearInterval(this.progressInterval);
        }
        
        // 显示进度条
        progressContainer.classList.remove('hidden');
        
        // 完全重置进度条状态 - 先停止所有动画
        progressBar.style.transition = 'none';
        progressBar.style.width = '100%';
        progressBar.style.background = 'linear-gradient(90deg, #22c55e, #22c55e)';
        progressBar.classList.remove('critical');
        
        // 强制重排以确保所有状态立即生效
        void progressBar.offsetWidth;
        void progressContainer.offsetHeight;
        
        // 设置新的过渡动画
        progressBar.style.transition = `width ${duration}ms linear, background ${duration}ms ease`;
        
        // 立即开始动画
        requestAnimationFrame(() => {
            progressBar.style.width = '0%';
        });
        
        // 颜色渐变效果
        const updateInterval = 50; // 每50ms更新一次颜色
        let elapsed = 0;
        this.progressInterval = setInterval(() => {
            if (!this.isGameActive || this.isGamePaused || !this.isWaitingForConfirmation) {
                clearInterval(this.progressInterval);
                return;
            }
            
            elapsed += updateInterval;
            const progress = elapsed / duration;
            
            if (progress >= 0.7) {
                // 最后30%时间变红色并开始脉冲
                progressBar.style.background = 'linear-gradient(90deg, #ef4444, #ef4444)';
                progressBar.classList.add('critical');
            } else if (progress >= 0.5) {
                // 中间时间变橙色
                progressBar.style.background = 'linear-gradient(90deg, #f97316, #f97316)';
            } else if (progress >= 0.3) {
                // 早期变黄色
                progressBar.style.background = 'linear-gradient(90deg, #eab308, #eab308)';
            }
        }, updateInterval);
        
        // 设置超时处理
        this.confirmationTimer = setTimeout(() => {
            if (this.isGameActive && !this.isGamePaused && this.isWaitingForConfirmation) {
                this.handleTimeout();
            }
        }, duration);
    }
    
    // 处理超时
    handleTimeout() {
        this.isWaitingForConfirmation = false;
        this.stopProgressTimer();
        
        // 根据游戏模式处理超时
        if (this.gameMode === 'life') {
            // 生命模式：扣除生命值
            this.lives--;
            this.showTimeoutFeedback();
            
            if (this.lives <= 0) {
                this.endGame();
                return;
            }
        } else {
            // 时间模式：当作错误答案处理
            this.showTimeoutFeedback();
        }
        
        this.totalAnswers++;
        this.updateUI();
        
        // 短暂延迟后生成下一题
        setTimeout(() => {
            this.generateQuestion();
        }, 1000);
    }
    
    // 停止进度条倒计时
    stopProgressTimer() {
        const progressContainer = document.getElementById('countdown-progress');
        const progressBar = document.getElementById('countdown-progress-bar');
        
        // 隐藏进度条
        progressContainer.classList.add('hidden');
        progressBar.classList.remove('critical');
        
        if (this.confirmationTimer) {
            clearTimeout(this.confirmationTimer);
            this.confirmationTimer = null;
        }
        
        if (this.progressInterval) {
            clearInterval(this.progressInterval);
            this.progressInterval = null;
        }
    }
    
    // 显示超时反馈
    showTimeoutFeedback() {
        const colorWordElement = document.getElementById('color-word');
        
        // 显示红色阴影效果表示超时
        colorWordElement.style.textShadow = '0 0 20px #ef4444';
        
        setTimeout(() => {
            colorWordElement.style.textShadow = '2px 2px 4px rgba(0,0,0,0.3)';
        }, 800);
    }
    
    
    // 回答问题
    answerQuestion(userAnswer) {
        if (!this.isGameActive || this.isGamePaused || !this.currentQuestion) return;
        
        // 停止所有计时器
        if (this.questionTimer) {
            clearTimeout(this.questionTimer);
        }
        
        // 停止进度条计时器
        if (!this.isWaitingForConfirmation) return; // 已经超时了
        this.isWaitingForConfirmation = false;
        this.stopProgressTimer();
        
        const isCorrect = userAnswer === this.currentQuestion.isCorrect;
        this.totalAnswers++;
        
        if (isCorrect) {
            this.correctAnswers++;
            this.showFeedback(true);
        } else {
            this.showFeedback(false);
            
            if (this.gameMode === 'life') {
                this.lives--;
                if (this.lives <= 0) {
                    this.endGame();
                    return;
                }
            }
        }
        
        this.updateUI();
        
        // 短暂延迟后生成下一个问题
        setTimeout(() => {
            this.generateQuestion();
        }, 500);
    }
    
    // 显示反馈
    showFeedback(isCorrect) {
        const colorWordElement = document.getElementById('color-word');
        
        if (isCorrect) {
            colorWordElement.style.textShadow = '0 0 20px #22c55e';
            setTimeout(() => {
                colorWordElement.style.textShadow = '2px 2px 4px rgba(0,0,0,0.3)';
            }, 300);
        } else {
            colorWordElement.style.textShadow = '0 0 20px #ef4444';
            setTimeout(() => {
                colorWordElement.style.textShadow = '2px 2px 4px rgba(0,0,0,0.3)';
            }, 300);
        }
    }
    
    
    // 更新UI
    updateUI() {
        // 更新题目统计
        document.getElementById('total-questions').textContent = this.totalAnswers;
        
        // 计算并更新正确率
        const accuracy = this.totalAnswers > 0 ? Math.round((this.correctAnswers / this.totalAnswers) * 100) : 0;
        document.getElementById('accuracy-display').textContent = accuracy + '%';
        
        // 更新计时器显示
        if (this.gameMode === 'time') {
            document.getElementById('timer-display').textContent = this.timeLeft;
        } else {
            document.getElementById('timer-display').textContent = '❤️'.repeat(this.lives);
        }
    }
    
    // 暂停游戏
    pauseGame() {
        if (!this.isGameActive) return;
        
        this.isGamePaused = true;
        document.getElementById('pause-menu').classList.remove('hidden');
        
        // 清理所有计时器
        if (this.questionTimer) {
            clearTimeout(this.questionTimer);
        }
        if (this.confirmationTimer) {
            clearTimeout(this.confirmationTimer);
        }
        if (this.progressInterval) {
            clearInterval(this.progressInterval);
        }
    }
    
    // 恢复游戏
    resumeGame() {
        if (!this.isGameActive) return;
        
        this.isGamePaused = false;
        document.getElementById('pause-menu').classList.add('hidden');
        
        // 重新开始当前问题的计时
        if (this.currentQuestion) {
            this.startProgressTimer(this.config.progressBarDuration);
        }
    }
    
    // 重新开始游戏
    restartGame() {
        this.cleanup();
        document.getElementById('pause-menu').classList.add('hidden');
        this.startGame(this.gameMode);
    }
    
    // 退出游戏
    quitGame() {
        this.cleanup();
        document.getElementById('pause-menu').classList.add('hidden');
        this.showScreen('main-menu');
    }
    
    // 结束游戏
    endGame() {
        this.isGameActive = false;
        this.cleanup();
        
        // 保存成绩
        this.saveScore();
        
        // 显示结果
        const accuracy = this.totalAnswers > 0 ? Math.round((this.correctAnswers / this.totalAnswers) * 100) : 0;
        const wrongAnswers = this.totalAnswers - this.correctAnswers;
        
        document.getElementById('final-total-questions').textContent = this.totalAnswers;
        document.getElementById('final-correct-answers').textContent = this.correctAnswers;
        document.getElementById('final-wrong-answers').textContent = wrongAnswers;
        document.getElementById('final-accuracy').textContent = accuracy + '%';
        
        this.showScreen('game-over');
    }
    
    // 清理定时器
    cleanup() {
        if (this.gameTimer) {
            clearInterval(this.gameTimer);
            this.gameTimer = null;
        }
        if (this.questionTimer) {
            clearTimeout(this.questionTimer);
            this.questionTimer = null;
        }
        if (this.confirmationTimer) {
            clearTimeout(this.confirmationTimer);
            this.confirmationTimer = null;
        }
        if (this.progressInterval) {
            clearInterval(this.progressInterval);
            this.progressInterval = null;
        }
        this.stopProgressTimer();
        this.isWaitingForConfirmation = false;
    }
    
    // 保存分数
    saveScore() {
        const scores = this.loadScores();
        const newScore = {
            username: this.username,
            totalAnswers: this.totalAnswers,
            correctAnswers: this.correctAnswers,
            accuracy: this.totalAnswers > 0 ? Math.round((this.correctAnswers / this.totalAnswers) * 100) : 0,
            mode: this.gameMode,
            date: new Date().toISOString()
        };
        
        scores.push(newScore);
        
        // 按题目数量排序，再按正确率排序，保留前20名
        scores.sort((a, b) => {
            if (b.totalAnswers !== a.totalAnswers) {
                return b.totalAnswers - a.totalAnswers; // 题目数多的排前面
            }
            return b.accuracy - a.accuracy; // 题目数相同时正确率高的排前面
        });
        scores.splice(20);
        
        localStorage.setItem('stroop-scores', JSON.stringify(scores));
    }
    
    // 加载分数
    loadScores() {
        const saved = localStorage.getItem('stroop-scores');
        return saved ? JSON.parse(saved) : [];
    }
    
    // 显示排行榜
    showLeaderboard() {
        const scores = this.loadScores();
        const listElement = document.getElementById('leaderboard-list');
        
        if (scores.length === 0) {
            listElement.innerHTML = '<div class="text-gray-400 text-center py-4">暂无记录</div>';
        } else {
            listElement.innerHTML = scores.map((score, index) => `
                <div class="flex justify-between items-center bg-white/10 rounded-lg p-3 ${index === 0 ? 'bg-gradient-to-r from-yellow-400/20 to-orange-400/20' : ''}">
                    <div class="flex items-center">
                        <span class="text-gray-300 w-6">#${index + 1}</span>
                        <span class="text-white font-medium ml-2">${score.username || '未知用户'}</span>
                    </div>
                    <div class="text-right">
                        <div class="text-white font-bold">${score.totalAnswers || 0}题</div>
                        <div class="text-gray-300 text-sm">${score.accuracy || 0}%</div>
                    </div>
                </div>
            `).join('');
        }
        
        this.showScreen('leaderboard-screen');
    }
}

// 初始化游戏
let game;
document.addEventListener('DOMContentLoaded', () => {
    game = new StroopGame();
});

// 防止页面滚动（移动端体验优化）
document.addEventListener('touchmove', function(e) {
    e.preventDefault();
}, { passive: false });

// 防止双击缩放
let lastTouchEnd = 0;
document.addEventListener('touchend', function(event) {
    const now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        event.preventDefault();
    }
    lastTouchEnd = now;
}, false);